package com.example.xianji.activity;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.R;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class XiuGaiPassWordActivity extends Activity implements OnClickListener {
    private ImageView xiugai_password_back;
    private ProgressDialog mCustomProgressDialog;
    private Button change_password_submit;
    //    private SharedPreferences sp;
//    private Editor ed;
    private EditText edittext_old_password, edittext_new_password, edittext_queren_password;

    private int[] oldpas_start_location, oldpas_end_location, newpas_start_location,
            newpas_end_location, surepas_start_location, surepas_end_location;

    private TextView start_textview_oldpassword, end_textview_oldpassword, end_textview_newpassword, start_textview_newpassword,
            end_textview_sure_newpassword, start_textview_sure_newpassword;
    private RelativeLayout relativelayout_sure_new_password, relativelayout_new_password, relativelayout_old_password;
    private boolean oldpas_flag = false, newpas_flag = false, surepas_flag = false;
    private int old_index = 1, new_index = 2, sure_index = 3;
    private Handler handle = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_xiu_gai_password);
        //XJApplication.getInstance().addActivity(this);
        xiugai_password_back = (ImageView) findViewById(R.id.xiugai_password_back);
        change_password_submit = (Button) findViewById(R.id.change_password_submit);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();

        edittext_old_password = (EditText) findViewById(R.id.edittext_old_password);
        edittext_new_password = (EditText) findViewById(R.id.edittext_new_password);
        edittext_queren_password = (EditText) findViewById(R.id.edittext_queren_password);
        edittext_old_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
        edittext_new_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
        edittext_queren_password.setTransformationMethod(PasswordTransformationMethod.getInstance());

        start_textview_oldpassword = (TextView) findViewById(R.id.start_textview_oldpassword);
        end_textview_oldpassword = (TextView) findViewById(R.id.end_textview_oldpassword);
        end_textview_newpassword = (TextView) findViewById(R.id.end_textview_newpassword);
        start_textview_newpassword = (TextView) findViewById(R.id.start_textview_newpassword);
        end_textview_sure_newpassword = (TextView) findViewById(R.id.end_textview_sure_newpassword);
        start_textview_sure_newpassword = (TextView) findViewById(R.id.start_textview_sure_newpassword);

        relativelayout_sure_new_password = (RelativeLayout) findViewById(R.id.relativelayout_sure_new_password);
        relativelayout_new_password = (RelativeLayout) findViewById(R.id.relativelayout_new_password);
        relativelayout_old_password = (RelativeLayout) findViewById(R.id.relativelayout_old_password);
        xiugai_password_back.setOnClickListener(this);
        change_password_submit.setOnClickListener(this);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        oldpas_start_location = new int[2];
        oldpas_end_location = new int[2];
        newpas_start_location = new int[2];
        newpas_end_location = new int[2];
        surepas_start_location = new int[2];
        surepas_end_location = new int[2];

        start_textview_oldpassword.getLocationInWindow(oldpas_start_location);
        end_textview_oldpassword.getLocationInWindow(oldpas_end_location);
        end_textview_newpassword.getLocationInWindow(newpas_end_location);
        start_textview_newpassword.getLocationInWindow(newpas_start_location);
        end_textview_sure_newpassword.getLocationInWindow(surepas_end_location);
        start_textview_sure_newpassword.getLocationInWindow(surepas_start_location);
        final ObjectAnimator oldpas_anima = ObjectAnimator.ofFloat(start_textview_oldpassword, "translationY", oldpas_end_location[1] - oldpas_start_location[1]);

        final ObjectAnimator newpas_anima = ObjectAnimator.ofFloat(start_textview_newpassword, "translationY", newpas_end_location[1] - newpas_start_location[1]);

        final ObjectAnimator surepas_anima = ObjectAnimator.ofFloat(start_textview_sure_newpassword, "translationY", surepas_end_location[1] - surepas_start_location[1]);

        final ValueAnimator old_value_anim = ValueAnimator.ofInt(20, 15);
        final ValueAnimator new_value_anim = ValueAnimator.ofInt(20, 15);
        final ValueAnimator sure_value_anim = ValueAnimator.ofInt(20, 15);
        final LinearInterpolator inter = new LinearInterpolator();

        /**
         * EditextView 的OnTouchListener监听
         */
        Edittext_OnTouchListener(edittext_old_password, oldpas_anima, inter, old_value_anim, start_textview_oldpassword);
        Edittext_OnTouchListener(edittext_new_password, newpas_anima, inter, new_value_anim, start_textview_newpassword);
        Edittext_OnTouchListener(edittext_queren_password, surepas_anima, inter, sure_value_anim, start_textview_sure_newpassword);

        /**
         * Relativelayout 的OnTouchListener监听
         */

        Relative_onTouchListener(relativelayout_old_password, oldpas_anima, inter, old_value_anim, start_textview_oldpassword, edittext_old_password, old_index);
        Relative_onTouchListener(relativelayout_new_password, newpas_anima, inter, new_value_anim, start_textview_newpassword, edittext_new_password, new_index);
        Relative_onTouchListener(relativelayout_sure_new_password, surepas_anima, inter, sure_value_anim, start_textview_sure_newpassword, edittext_queren_password, sure_index);


        final ObjectAnimator oldpas_big_anima = ObjectAnimator.ofFloat(start_textview_oldpassword, "translationY", oldpas_end_location[1] - oldpas_end_location[1]);

        final ObjectAnimator newpas_big_anima = ObjectAnimator.ofFloat(start_textview_newpassword, "translationY", newpas_end_location[1] - newpas_end_location[1]);

        final ObjectAnimator surepas_big_anima = ObjectAnimator.ofFloat(start_textview_sure_newpassword, "translationY", surepas_end_location[1] - surepas_end_location[1]);

        final ValueAnimator old_value_big_anim = ValueAnimator.ofInt(15, 20);

        final ValueAnimator new_value_big_anim = ValueAnimator.ofInt(15, 20);
        final ValueAnimator sure_value_big_anim = ValueAnimator.ofInt(15, 20);


        /**
         * 焦点改变
         */

        edittext_old_password.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus && edittext_old_password.getText().toString().length() == 0) {

                    Log.i("旧密码失去焦点", "旧密码失去焦点");
                    oldpas_flag = false;
                    Animator_start(oldpas_big_anima, old_value_big_anim, inter, start_textview_oldpassword, getResources().getColor(R.color.gray75));


                } else if (hasFocus) {
                    Log.i("旧密码获取焦点", "旧密码获取焦点");
                    if (oldpas_flag == false) {
                        Animator_start(oldpas_anima, old_value_anim, inter, start_textview_oldpassword, getResources().getColor(R.color.blue22));
                    }

                    edittext_old_password.requestFocus();
                    edittext_old_password.setCursorVisible(true);
                    InputMethodManager imm = (InputMethodManager) edittext_old_password.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                }
            }
        });

        edittext_new_password.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus && edittext_new_password.getText().toString().length() == 0) {

                    Log.i("新密码失去焦点", "新密码失去焦点");

                    Animator_start(newpas_big_anima, new_value_big_anim, inter, start_textview_newpassword, getResources().getColor(R.color.gray75));
                    newpas_flag = false;


                } else if (hasFocus) {
                    Log.i("新密码获取焦点", "新密码获取焦点");
                    if (newpas_flag == false) {
                        Animator_start(newpas_anima, new_value_anim, inter, start_textview_newpassword, getResources().getColor(R.color.blue22));
                    }
                    edittext_new_password.requestFocus();
                    edittext_new_password.setCursorVisible(true);
                    InputMethodManager imm = (InputMethodManager) edittext_new_password.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                }
            }
        });

        edittext_queren_password.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus && edittext_new_password.getText().toString().length() == 0) {
                    Animator_start(surepas_big_anima, sure_value_big_anim, inter, start_textview_sure_newpassword, getResources().getColor(R.color.gray75));
                    surepas_flag = false;
                } else if (hasFocus) {
                    if (surepas_flag == false) {
                        Animator_start(surepas_anima, sure_value_anim, inter, start_textview_sure_newpassword, getResources().getColor(R.color.blue22));
                    }
                    edittext_queren_password.requestFocus();
                    edittext_queren_password.setCursorVisible(true);
                    InputMethodManager imm = (InputMethodManager) edittext_queren_password.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                }
            }
        });
    }

    private void Relative_onTouchListener(RelativeLayout relative, final ObjectAnimator anima, final LinearInterpolator inter, final ValueAnimator value_anim,
                                          final TextView textview, final EditText edittext, final int index) {
        relative.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (index == 1) {
                        if (oldpas_flag == false) {
                            Animator_start(anima, value_anim, inter, textview, getResources().getColor(R.color.blue22));
                            oldpas_flag = true;
                        }

                    } else if (index == 2) {
                        if (newpas_flag == false) {
                            Animator_start(anima, value_anim, inter, textview, getResources().getColor(R.color.blue22));
                            newpas_flag = true;
                        }

                    } else if (index == 3) {
                        if (surepas_flag == false) {
                            Animator_start(anima, value_anim, inter, textview, getResources().getColor(R.color.blue22));
                            surepas_flag = true;
                        }
                    }
                    edittext.requestFocus();
                    edittext.setCursorVisible(true);
                    InputMethodManager imm = (InputMethodManager) edittext.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
                    return false;
                }
                return false;
            }
        });
    }

    private void Edittext_OnTouchListener(EditText edittext, final ObjectAnimator anima, final LinearInterpolator inter,
                                          final ValueAnimator value_anim, final TextView textview) {
        edittext.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Animator_start(anima, value_anim, inter, textview, getResources().getColor(R.color.blue22));
                return false;
            }
        });
    }

    private void Animator_start(ObjectAnimator anima,
                                ValueAnimator value_anim, LinearInterpolator inter,
                                final TextView textview, final int color) {
        anima.setInterpolator(inter);
        anima.setDuration(300);
        anima.start();
        value_anim.setDuration(300);
        value_anim.setInterpolator(inter);
        value_anim.start();

        value_anim.addUpdateListener(new AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                textview.setTextSize((Integer) animation.getAnimatedValue());
                textview.setTextColor(color);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.xiugai_password_back) {
            this.finish();
        } else if (v.getId() == R.id.change_password_submit) {
            if (edittext_old_password.getText().toString().length() > 0) {
                if (edittext_new_password.getText().toString().length() > 5) {
                    if (edittext_queren_password.getText().toString().equals(edittext_new_password.getText().toString())) {
                        mCustomProgressDialog = new ProgressDialog(this);
                        mCustomProgressDialog.setCanceledOnTouchOutside(false);
                        mCustomProgressDialog.show();
                        change_password();
                    } else {
                        Toast.makeText(XiuGaiPassWordActivity.this, "输入的新密码和确认密码要保持一致", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(XiuGaiPassWordActivity.this, "请输入新密码", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(XiuGaiPassWordActivity.this, "请输入原始密码", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void change_password() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("password", edittext_new_password.getText().toString());
        parms.addBodyParameter("password_confirmation", edittext_queren_password.getText().toString());
        parms.addBodyParameter("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        parms.addBodyParameter("oldpass", edittext_old_password.getText().toString());
        httpUtils.send(HttpMethod.POST, Contant.change_password, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                handle.sendEmptyMessage(1);
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {

                    JSONObject obj = new JSONObject(arg0.result);
                    if (obj.getInt("status") == 1) {
                        Toast.makeText(XiuGaiPassWordActivity.this, obj.getString("msg"), Toast.LENGTH_SHORT).show();
                        XiuGaiPassWordActivity.this.setResult(Contant.change_password_success_resultCode);
                        startActivity(new Intent(XiuGaiPassWordActivity.this, Main_LoginActivity.class));
                        //修改成功后跳转到登录页面，如果点登录页面的返回键，则我的后台重新请求数据，
                        Contant.change_password_login = 1;
                        XiuGaiPassWordActivity.this.finish();
                    } else {

                        Toast.makeText(XiuGaiPassWordActivity.this, obj.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                    handle.sendEmptyMessage(1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
